﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Data.OleDb;
using System.IO;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using CentaLine.Infrastructure;
using CentaLine.Model;
using CentaLine.Repository;

namespace CentaLine.Site.Controllers
{
    public class CommonController : Controller
    {

        DirectorManager dm;
        VitualPhoneManager vp;
        public CommonController()
        {
            dm = new DirectorManager();
            vp = new VitualPhoneManager();
        }
        
        public PartialViewResult UpLoadPartPage()
        {
            return new PartialViewResult();
        }

        public JsonResult Swfupload()
        {
            CommResult res = new CommResult();
            try
            {
                string uploadsFolder = HttpContext.Server.MapPath("~/Upload");
                string fileNamed = DateTime.Now.ToString("yyyyMMddHHmmssfffffff");
                var httpfile = Request.Files["Filedata"];
                string fileName = httpfile.FileName;
                string fileExtension = fileName.Substring(fileName.LastIndexOf('.'));
                if (httpfile != null)
                {
                    if (fileExtension.IndexOf("xls") == -1)
                    {
                        res.Result = false;
                        res.Exception = "文件格式有误";
                        return Json(res);
                    }
                    var uploadsPath = Path.Combine(uploadsFolder, fileNamed + fileExtension);
                    httpfile.SaveAs(uploadsPath);
                    var ds = CommonHelper.LoadDataFromExcel(uploadsPath);
                    var resT = vp.AddVitualPhoneToDB(ds);
                    if (resT.Result)
                    {
                        res.Result = true;
                        res.Message = "数据总数:" + ds.Tables[0].Rows.Count + "上传成功:" + resT.Message + "条数据";
                    }
                    else
                    {
                        res.Result = false;
                        res.Exception = "数据总数:" + ds.Tables[0].Rows.Count + "上传成功:" + resT.Message + "条数据\n" + resT.Exception;
                    }
                }
                else
                {
                    res.Result = false;
                    res.Message = "没有文件";
                }
            }
            catch (Exception e)
            {
                res.Result = false;
                res.Exception = e.Message;
            }
            return Json(res);
        }
    }
}
